#!/usr/bin/env python
''' orientxxi.info '''
from datetime import datetime
from zoneinfo import ZoneInfo

from calibre import browser
from calibre.web.feeds.news import BasicNewsRecipe


class OrientXXIRecipe(BasicNewsRecipe):
    title = 'Orient XXI'
    __author__ = 'Kabonix'
    description = 'Magazine en ligne sur le Monde arabe et musulman'
    language = 'fr'
    oldest_article = 30
    max_articles_per_feed = 50
    auto_cleanup = False
    encoding = 'utf-8'
    use_embedded_content = True
    no_stylesheets = True
    remove_javascript = True
    scale_news_images_to_device = True

    feeds = [
        ('Orient XXI', 'https://orientxxi.info/?page=backend&lang=fr')
    ]

    extra_css = '''
        img { max-width: 100%; height: auto; display: block; margin: 1em auto; }
        h1 { font-size: 2em; margin: 1em 0; }
        h2 { font-size: 1.5em; margin: 1em 0; }
    '''

    def default_cover(self, cover_file):
        '''
        Crée une couverture personnalisée avec le logo
        '''
        from qt.core import QColor, QFont, QImage, QPainter, QPen, QRect, Qt

        from calibre.gui2 import ensure_app, load_builtin_fonts, pixmap_to_data
        try:
            ensure_app()
            load_builtin_fonts()

            today = datetime.now(ZoneInfo('Europe/Paris'))
            wkd = today.weekday()
            french_weekday = {0:'Lundi',1:'Mardi',2:'Mercredi',3:'Jeudi',4:'Vendredi',5:'Samedi',6:'Dimanche'}
            french_month = {1:'janvier', 2:'février', 3:'mars', 4:'avril', 5:'mai', 6:'juin',
                            7:'juillet', 8:'août', 9:'septembre', 10:'octobre', 11:'novembre', 12:'décembre'}

            weekday = french_weekday[wkd]
            month = french_month[today.month]
            date_str = f'{weekday} {today.day} {month} {today.year}'
            edition = today.strftime('Édition de %Hh')

            # Image de base
            img = QImage(1400, 1920, QImage.Format_RGB888)
            img.fill(QColor('orange'))  # Fond orange

            # Charger le logo
            logo_url = 'https://upload.wikimedia.org/wikipedia/fr/1/15/Orient_XXI.png'
            br = browser()
            logo_data = br.open(logo_url).read()
            logo = QImage()
            logo.loadFromData(logo_data)

            # Redimensionner le logo (garder les proportions)
            logo_width = 800  # Largeur souhaitée
            scaled_logo = logo.scaledToWidth(logo_width, Qt.SmoothTransformation)

            # Position du logo (centré)
            x = (img.width() - scaled_logo.width()) // 2
            y = (img.height() - scaled_logo.height()) // 2 - 100  # Un peu au-dessus du centre

            # Dessiner le logo
            p = QPainter(img)
            p.drawImage(x, y, scaled_logo)
            p.end()

            # Ajouter la date
            p = QPainter(img)
            p.setPen(QPen(QColor('black')))

            font = QFont('Liberation Sans', 36)
            p.setFont(font)

            r = QRect(0, y + scaled_logo.height() + 50, img.width(), 100)
            p.drawText(r, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter, date_str)

            # Ajouter l'édition
            font.setItalic(True)
            font.setPointSize(32)
            p.setFont(font)

            r = QRect(0, y + scaled_logo.height() + 150, img.width(), 100)
            p.drawText(r, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter, edition)

            p.end()

            # Sauvegarder
            img_data = pixmap_to_data(img)
            cover_file.write(img_data)
            cover_file.flush()
            return True
        except Exception as e:
            self.log.error(f'Erreur lors de la création de la couverture: {e}')
            return False
